package com.shangxian.giveithome.service.impl;

import com.shangxian.giveithome.code.CommonCode;
import com.shangxian.giveithome.code.IssueCode;
import com.shangxian.giveithome.entity.PageableDetails;
import com.shangxian.giveithome.entity.UserDetails;
import com.shangxian.giveithome.entity.community.*;
import com.shangxian.giveithome.exception.ExceptionUtils;
import com.shangxian.giveithome.mapper.*;
import com.shangxian.giveithome.result.Result;
import com.shangxian.giveithome.service.IssueService;
import com.shangxian.giveithome.utils.PageUtils;
import com.shangxian.giveithome.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IssueServiceImpl implements IssueService {

    @Autowired
    private IssueMapper issueMapper;

    @Autowired
    private AttentionMapper attentionMapper;

    @Autowired
    private IssueImgMapper issueImgMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CollectionsMapper collectionsMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private HttpServletRequest request;


    @Override
    @Transactional
    public IssueDetails findIssueDetails(Long id, HttpServletRequest request) {
        issueMapper.updateLookIssueCount(id);
        IssueDetails issueDetails = issueMapper.findIssueDetails(id);
        if (issueDetails == null || issueDetails.getId() == null || issueDetails.getId().equals("")) {
            return new IssueDetails();
        }
        else {
                UserDetails userDetails = redisUtils.getHeader(request);
                if (userDetails != null || "".equals(userDetails)) {
                    if (userDetails.getId().equals(issueDetails.getUserId())) {
                        issueDetails.setState(2);
                    } else {
                        LookArticle lookArticle = new LookArticle();
                        lookArticle.setIssueId(issueDetails.getId());
                        lookArticle(lookArticle, request);
                        int i = attentionMapper.findAttentionState(userDetails.getId(), issueDetails.getUserId());
                        System.out.println(i);
                        if (i > 0) {
                            issueDetails.setState(1);
                        }
                    }
                }
        if (issueDetails.getCollectionId() == null || issueDetails.getCollectionId().equals("") || issueDetails.getCollectionId() == 0) {
            issueDetails.setCollectionName("");
        } else {
            CollectionsList collection = collectionsMapper.findCollection(issueDetails.getCollectionId());
            issueDetails.setCollectionName(collection.getCollectionsName());
            issueDetails.setIssueNumber(collection.getIssueNumber());
        }
        UserList userList = attentionMapper.findUserList(issueDetails.getUserId());
        if (issueDetails.getImgId() == null || issueDetails.getImgId().equals("")) {
            issueDetails.setImgs(new ArrayList<>());
        }
        if (issueDetails.getImgId() != null && issueDetails.getImgId() > 0) {
            List<IssueImg> issueImg = issueImgMapper.findIssueImgById(issueDetails.getImgId());
            issueDetails.setImgs(issueImg);
        }
        issueDetails.setName(userList.getName());
        issueDetails.setPicture(userList.getPicture());
        return issueDetails;
    }

}

    @Override
    public PageableDetails findAllQandAList(Pageable pageable,String screenSearch) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        int total = issueMapper.findAllQandAArticlrCount(screenSearch);
        if (total ==0){
            return new PageableDetails(pageNumber,pageSize,total,returnPages(total,pageSize),new ArrayList<>());
        }
        List<IssueList> allQandAList = issueMapper.findAllQandAList(pageNumber * pageSize, pageSize,screenSearch);
        if (allQandAList.size() !=0) {
            List<Long> imgIds = allQandAList.stream().map(IssueList::getImgId).collect(Collectors.toList());
            List<Long> userIds = allQandAList.stream().map(IssueList::getUserId).collect(Collectors.toList());
            List<Long> collectIds = allQandAList.stream().map(IssueList::getCollectionId).collect(Collectors.toList());
            List<CollectionsList> collectionsLists = collectionsMapper.findCollectionsLists(collectIds);
            List<IssueImg> imgs = issueImgMapper.findIssueImgByIds(imgIds);
            List<UserList> userLists = userMapper.findAllUserMessageById(userIds);
            allQandAList.forEach(IssueList -> {
                    IssueList.setCollectionName("");
                    IssueList.setImgPath("");
                for (IssueImg issueImg:imgs) {
                    if (IssueList.getImgId() != null && IssueList.getImgId().equals(issueImg.getKeyId())){
                        IssueList.setImgPath(issueImg.getPath());
                        break;
                    }
                }
                for (UserList userList : userLists) {
                    if (IssueList.getUserId() != null && IssueList.getUserId().equals(userList.getId())){
                        IssueList.setName(userList.getName());
                        IssueList.setPicture(userList.getPicture());
                        break;
                    }
                }
                for (CollectionsList collectionsList : collectionsLists) {
                    if (IssueList.getCollectionId() != null && IssueList.getCollectionId().equals(collectionsList.getId())){
                        IssueList.setCollectionName(collectionsList.getCollectionsName());
                    }
                }
            });
        }
        return new PageableDetails<>(pageNumber,pageSize,total,returnPages(total,pageSize),allQandAList);
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void issueArticle(Issue issue, HttpServletRequest request) {
        UserDetails userDetails = redisUtils.getHeader(request);
        if (userDetails ==null){
            ExceptionUtils.error(CommonCode.AUTH_NOT_SUCCESS);
        }
        issue.setUserId(userDetails.getId());
        issue.setIssueTime(new Date());
        issue.setState(0);
        issue.setLookNumber(0);
        int i = issueMapper.issueArticle(issue);
        if (i<1){
            Result.error(IssueCode.UPLOAD_ERROR);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void lookArticle(LookArticle lookArticle, HttpServletRequest request) {
        UserDetails userDetails = redisUtils.getHeader(request);
        lookArticle.setUserId(userDetails.getId());
        int count = issueMapper.findUserLookArticle(userDetails.getId(), lookArticle.getIssueId());
        if (count < 1) {
            lookArticle.setLookTime(new Date());
            int i = issueMapper.lookArticle(lookArticle);
            if (i < 1) {
                ExceptionUtils.error(CommonCode.DATA_ERROR);
            }
        }
    }

    /**
     * 查询用户的文章列表
     * @param pageable
     * @param id
     * @param request
     * @return
     */
    @Override
    public PageableDetails findUserIssueList(Pageable pageable, Long id, HttpServletRequest request) {
        int pageSize = pageable.getPageSize();
        int pageNumber = pageable.getPageNumber();
        if (id ==null && redisUtils.getHeader(request) ==null){
              ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        if (id != null) {
            int total = issueMapper.findUserIssueArticleCount(id);
            if (total == 0) {
                return new PageableDetails<>(pageNumber, pageSize, total, returnPages(total, pageSize), new ArrayList<>());
            }

            List<IssueList> issueList = issueMapper.findUserIssueArticleList(id, pageNumber * pageSize, pageSize);
            if (issueList.size() !=0) {
                UserList userLists = attentionMapper.findUserList(id);
                List<Long> ids = issueList.stream().map(IssueList::getImgId).collect(Collectors.toList());
                List<Long> collectionIds = issueList.stream().map(IssueList::getCollectionId).collect(Collectors.toList());
                List<CollectionsList> collections = collectionsMapper.findCollectionsLists(collectionIds);
                List<IssueImg> issueImgs = issueImgMapper.findIssueImgByIds(ids);
                issueList.forEach(attentionDetails1 -> {
                    attentionDetails1.setName(userLists.getName());
                    attentionDetails1.setPicture(userLists.getPicture());
                    attentionDetails1.setCollectionName("");
                    attentionDetails1.setImgPath("");
                    for (IssueImg issueImg : issueImgs) {
                        if (attentionDetails1.getImgId() != null && attentionDetails1.getImgId().equals(issueImg.getKeyId())) {
                            attentionDetails1.setImgPath(issueImg.getPath());
                            break;
                        }
                    }
                    for (CollectionsList collection : collections) {
                        if (attentionDetails1.getCollectionId() != null && attentionDetails1.getCollectionId().equals(collection.getId())) {
                            attentionDetails1.setCollectionName(collection.getCollectionsName());
                            break;
                        }
                    }
                });
            }

            return new PageableDetails<>(pageNumber, pageSize, total, returnPages(total, pageSize), issueList);
        }
        UserDetails userDetails = redisUtils.getHeader(request);
        int total = issueMapper.findUserIssueArticleCount(userDetails.getId());
        if (total == 0) {
            return new PageableDetails<>(pageNumber, pageSize, total, returnPages(total, pageSize), new ArrayList<>());
        }
        List<IssueList> issueList = issueMapper.findUserIssueArticleList(userDetails.getId(), pageNumber * pageSize, pageSize);
        if (issueList.size() !=0) {
            UserList userLists = attentionMapper.findUserList(userDetails.getId());
            List<Long> ids = issueList.stream().map(IssueList::getImgId).collect(Collectors.toList());
            List<Long> collectionIds = issueList.stream().map(IssueList::getCollectionId).collect(Collectors.toList());
            List<CollectionsList> collections = collectionsMapper.findCollectionsLists(collectionIds);
            List<IssueImg> issueImgs = issueImgMapper.findIssueImgByIds(ids);
            issueList.forEach(attentionDetails1 -> {
                attentionDetails1.setName(userLists.getName());
                attentionDetails1.setPicture(userLists.getPicture());
                attentionDetails1.setCollectionName("");
                attentionDetails1.setImgPath("");
                for (IssueImg issueImg : issueImgs) {
                    if (attentionDetails1.getImgId() != null && attentionDetails1.getImgId().equals(issueImg.getKeyId())) {
                        attentionDetails1.setImgPath(issueImg.getPath());
                        break;
                    }
                }
                for (CollectionsList collection : collections) {
                    if (attentionDetails1.getCollectionId() != null && attentionDetails1.getCollectionId().equals(collection.getId())) {
                        attentionDetails1.setCollectionName(collection.getCollectionsName());
                        break;
                    }
                }
            });
        }
        return new PageableDetails<>(pageNumber, pageSize, total, returnPages(total, pageSize), issueList);
    }

    @Override
    public PageableDetails findAllAttentionUserIssueList(Pageable pageable, HttpServletRequest request) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        UserDetails userDetails = redisUtils.getHeader(request);
        int count = attentionMapper.attentionUserCount(userDetails.getId());
        if (count ==0){
            return new PageableDetails<>(pageNumber,pageSize,count,returnPages(count,pageSize),new ArrayList<>());
        }
        List<Long> userIds = attentionMapper.findAttentionIds(userDetails.getId());
        int total = issueMapper.findAllAttentionUserIssueCount(userIds);
        List<IssueList> issueList = issueMapper.findAllAttentionUserIssueList( pageNumber * pageSize, pageSize,userIds);
        if (issueList.size() !=0) {
            List<AttentionUserList> attentionUserLists = attentionMapper.findAllAttentionUsers(userIds);
            List<Long> ids = issueList.stream().map(IssueList::getImgId).collect(Collectors.toList());
            List<Long> collectionIds = issueList.stream().map(IssueList::getCollectionId).collect(Collectors.toList());
            List<CollectionsList> collections = collectionsMapper.findCollectionsLists(collectionIds);
            List<IssueImg> issueImgs = issueImgMapper.findIssueImgByIds(ids);
            issueList.forEach(attentionDetails1 -> {
                    attentionDetails1.setCollectionName("");
                    attentionDetails1.setImgPath("");
                    attentionDetails1.setPicture("");
                    attentionDetails1.setName("");
                for (AttentionUserList attentionUserList : attentionUserLists) {
                    if (attentionDetails1.getUserId() != null && attentionDetails1.getUserId().equals(attentionUserList.getId())) {
                        attentionDetails1.setName(attentionUserList.getName());
                        attentionDetails1.setPicture(attentionUserList.getPicture());
                        break;
                    }
                }
                    for (CollectionsList collection : collections) {
                        if (attentionDetails1.getCollectionId() != null && attentionDetails1.getCollectionId().equals(collection.getId())) {
                            attentionDetails1.setCollectionName(collection.getCollectionsName());
                            break;
                        }
                    }
                    for (IssueImg issueImg : issueImgs) {
                        if (attentionDetails1.getImgId() != null && attentionDetails1.getImgId().equals(issueImg.getKeyId())) {
                            attentionDetails1.setImgPath(issueImg.getPath());
                            break;
                        }
                    }
            });
        }
        return new PageableDetails<>(pageNumber, pageSize, total, returnPages(total, pageSize), issueList);
    }

    @Override
    public void deleteArticle(Long id) {
        int i = issueMapper.deleteArticle(id);
        if (i<1){
            ExceptionUtils.error(CommonCode.DATA_ERRORS);
        }
    }


    @Override
    public PageableDetails findAllIssue(Pageable pageable) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        int total = issueMapper.findAllIssueCount();
        if (total ==0){
            return new PageableDetails<>(pageNumber,pageSize,total,returnPages(total,pageSize),new ArrayList<>());
        }
        List<IssueList> allIssueArticleList = issueMapper.findAllIssueArticleList(pageNumber * pageSize, pageSize);
        if(allIssueArticleList.size()!=0){
            List<Long> imgIds = allIssueArticleList.stream().map(IssueList::getImgId).collect(Collectors.toList());
            List<Long> collectionIds = allIssueArticleList.stream().map(IssueList::getCollectionId).collect(Collectors.toList());
            List<Long> userId = allIssueArticleList.stream().map(IssueList::getUserId).collect(Collectors.toList());
            List<IssueImg> imgs = issueImgMapper.findIssueImgByIds(imgIds);
            List<CollectionsList> collectionsLists = collectionsMapper.findCollectionsLists(collectionIds);
            List<UserList> userMessages = userMapper.findAllUserMessageById(userId);
            allIssueArticleList.forEach(allIssueArticle -> {
                    allIssueArticle.setCollectionName("");
                    allIssueArticle.setImgPath("");
                for (IssueImg img : imgs) {
                    if (allIssueArticle.getImgId() != null && allIssueArticle.getImgId().equals(img.getKeyId())) {
                        allIssueArticle.setImgPath(img.getPath());
                        break;
                    }
                }
                for (CollectionsList collectionsList : collectionsLists) {
                    if (allIssueArticle.getCollectionId() != null && allIssueArticle.getCollectionId().equals(collectionsList.getId())) {
                        allIssueArticle.setCollectionName(collectionsList.getCollectionsName());
                        break;
                    }
                }
                for (UserList userMessage : userMessages) {
                    if (allIssueArticle.getUserId() != null && allIssueArticle.getUserId().equals(userMessage.getId())) {
                        allIssueArticle.setName(userMessage.getName());
                        allIssueArticle.setPicture(userMessage.getPicture());
                        break;
                    }
                }
            });
        }
        return new PageableDetails<>(pageNumber,pageSize,total,returnPages(total,pageSize),allIssueArticleList);
    }





















    /**
     * 返回
     *
     * @param pageNumber 当前页
     * @param pageSize   每页条数
     * @param count      总条数
     * @param list       返回数据
     * @param <T>        泛型
     * @return
     */
    public <T> PageableDetails returnPageable(int pageNumber, Integer pageSize, Integer count, List<T> list) {
        return new PageableDetails<>(pageNumber, pageSize, count, list);
    }


    /**
     * 返回总页数
     *
     * @param total
     * @param pageSize
     * @return
     */
    public int returnPages(int total, int pageSize) {
        return PageUtils.returnPages(total, pageSize);
    }
}
